/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package pl.put.dcs.core.workflow.serializer;


import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Logger;
import org.netbeans.api.project.Project;
import org.openide.filesystems.FileLock;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.util.Exceptions;
import pl.put.dcs.core.utils.serializer.SerializeManager;
import pl.put.dcs_modeler.utils.FlowModelUtil;
import pl.put.model.flowModel.FlowModel;
/**
 * Serializer, ktory ma ulatwic pozniejsze przejscie na xpdl. Wszystkie klasy z dcs-core sa dystrybuowane, tj. wystepuja one, takze w serwerze aplikacji.
 * Ulatwia to publikacje projektu na serwer.
 *
 * @author LukaszR
 */
public class WorkflowSerializer
{
    public static Logger log = Logger.getLogger( WorkflowSerializer.class.getName() );
    public static final String FLOW_MODEL_REMOTE_POSTFIX = "remote";

    public static String serializeFlow( FlowModel flowModel )
    {
        SerializeManager sm = new SerializeManager();
        return sm.serializeToString( flowModel );
    }

    public static void serializeFlowModelRemoteToFile( FlowModel flowModel, Project project )
    {
        String serializedFlow = serializeFlow( flowModel );
        try
        {
            File file = new File( project.getProjectDirectory().getPath() + "/" + FlowModelUtil.getSerializedFlowModelPath( project ) + FLOW_MODEL_REMOTE_POSTFIX );
            FileObject fo = FileUtil.createData( file );
            FileLock lock = new FileLock();
            try
            {
                lock = fo.lock();
            }
            catch ( IOException iOException )
            {
                log.warning( "writeString(): File is locked. Can't write." );
                iOException.printStackTrace();
            }
            PrintWriter to = null;
            try
            {
                to = new PrintWriter( fo.getOutputStream( lock ) );
                try
                {
                    to.print( serializedFlow );
                } finally
                {
                    to.close();
                }
            }
            catch ( IOException ex )
            {
                log.warning( "writeString(): Error creatig PrintWriter" );
                Exceptions.printStackTrace( ex );
            } finally
            {
                lock.releaseLock();
                to.flush();
                to.close();
            }
        }
        catch ( IOException ex )
        {
            Exceptions.printStackTrace( ex );
        }

    }

    public FlowModel unserializeFlow()
    {
        return new FlowModel( "Dsds" );
    }

}
